package com.qd.system.importexcel.systemset;

import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.sys.domain.entity.system.SystemSetDTO;
import com.qd.system.model.SystemSet;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.system.SystemSetService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static java.util.stream.Collectors.toList;

/**
 * 系统设置,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
@RequiredArgsConstructor
public class SystemSetImportHandler {

    private final SystemSetService systemSetService;
    private final ValidatorUtil validatorUtil;
    private final List<ImportErr> errorList;

    private final LocalDateTime now = LocalDateTime.now();

    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<SystemSetDTO>> rowList, List<BatchResult> results) {
        final List<SystemSetDTO> systemSetList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<String> existsIds = existsIds(systemSetList);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<SystemSetDTO> excelRowMsg : rowList) {
                final SystemSetDTO systemSetDTO = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                final List<String> errors = buildImportDTO(systemSetDTO);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<SystemSet> addSystemSetList = new ArrayList<>(size);
                final List<SystemSet> updateSystemSetList = new ArrayList<>(size);
                doProcessDictData(existsIds, systemSetList, addSystemSetList, updateSystemSetList);
                BatchResult.buildBatchResult(results, addSystemSetList.size(), updateSystemSetList.size());
                addSystemSetList.clear();
                updateSystemSetList.clear();
            }
        } finally {
            systemSetList.clear();
            existsIds.clear();
        }
    }

    /**
     * 保存数据
     *
     * @param existsIds           已经存在的数据库主键
     * @param systemSetList       excel行数据集合
     * @param addSystemSetList    添加集合
     * @param updateSystemSetList 更新集合
     */
    private void doProcessDictData(List<String> existsIds, List<SystemSetDTO> systemSetList, List<SystemSet> addSystemSetList, List<SystemSet> updateSystemSetList) {
        systemSetList.forEach(systemSetDTO -> {
            final SystemSet systemSet = systemSetService.dtoToModel(systemSetDTO);
            systemSetService.clearCache(systemSet);
            if (MbUtil.isExistInCollection(existsIds, systemSetDTO.getCode())) {
                systemSet.setAddTime(null);
                systemSet.setUpdateTime(now);
                updateSystemSetList.add(systemSet);
            } else {
                systemSet.setAddTime(now);
                systemSet.setUpdateTime(null);
                addSystemSetList.add(systemSet);
            }
        });
        if (!addSystemSetList.isEmpty()) {
            systemSetService.saveBatch(addSystemSetList);
        }
        if (!updateSystemSetList.isEmpty()) {
            systemSetService.updateBatchIds(updateSystemSetList);
        }
    }

    /**
     * 获得主键存在的集合
     *
     * @param systemSetList excel行数据集合
     * @return 主键集合
     */
    private List<String> existsIds(List<SystemSetDTO> systemSetList) {
        final List<String> ids = systemSetList.stream().map(SystemSetDTO::getCode).collect(toList());
        final List<String> existsIds = systemSetService.getBaseMapper().getIds(ids);
        ids.clear();
        return existsIds;
    }

    /**
     * 导入验证
     *
     * @param systemSetDTO 单个excel行数据
     * @return 异常信息
     */
    private List<String> buildImportDTO(SystemSetDTO systemSetDTO) {
        final List<String> errors = new ArrayList<>();
        //验证信息，自己编写
        Optional.ofNullable(systemSetDTO.getTypeDisplay()).ifPresent(s -> {
            if (s.equals("是")) {
                systemSetDTO.setType(0);
            }
            if (s.equals("否")) {
                systemSetDTO.setType(1);
            }
        });
        importValidate(systemSetDTO, errors);
        return errors;
    }

    /**
     * 导入实体验证
     *
     * @param systemSetDTO 单个excel行数据
     * @param errors       异常信息存储
     */
    private void importValidate(SystemSetDTO systemSetDTO, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(systemSetDTO, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}